from rest_framework import serializers
from rest_framework.response import Response

from activity.models import Activity, SignUp


class ActivityListSerializer(serializers.ModelSerializer):
    is_apply = serializers.BooleanField(read_only=True, default=False)

    class Meta:
        model = Activity
        fields = ('id', 'name', 'published_time', 'host_city', 'image_url', 'is_apply')


class ActivityRetrieveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Activity
        exclude = ('on_deleted',)


class ActivityApplySerializer(serializers.Serializer):
    user_id = serializers.IntegerField(read_only=True)
    activity_id = serializers.IntegerField()

    def validate(self, attrs):
        # 获取活动id
        activity_id = attrs['activity_id']

        # 获取用户id
        user_id = self.context['request'].user.id

        # 校验活动是否存在
        activity = Activity.objects.get(id=activity_id)
        if not activity:
            raise serializers.ValidationError('活动不存在')

        # 查询数据库活动是否报名
        if SignUp.objects.filter(activity_id=activity_id, user_id=user_id):
            raise serializers.ValidationError('您已报名')
            # return Response({'message': '您已报名'})
        attrs['user_id'] = user_id
        return attrs

    def create(self, validated_data):

        # 创建活动报名对象
        sign_up_obj = SignUp()
        sign_up_obj.user_id = validated_data['user_id']
        sign_up_obj.activity_id = validated_data['activity_id']
        sign_up_obj.save()

        return sign_up_obj